//执行sql任务
let Sql_Task_Object = {
   "field": function(n,t){ return Apps.field("change_sql_task", n, t); },
   "reload": function(){ this.list(); },
   "editor": null,
   "menu": function(e, i, r){
       e.preventDefault();//阻止浏览器自带的右键菜单弹出
       let m = $('#sql_task_menu');

       let dats = $(this).datagrid("getSelections");
       if(dats.length < 1){ $(this).datagrid('selectRow',i); }

       if(m.children("div:not([class*='menu-line'])").length > 0){
          m.menu('show', {left:e.pageX, top:e.pageY, hideOnUnhover:false});
       }
   },
   "init":function(){
         $("#change_sql_task > div#sql_tabs div.sql_history > div > li").click(function(){
               $(this).parent().find("> li").removeClass('sel');
               $(this).addClass('sel');
         });
   },
   "list": function(page, limit){
          let dg = $("#sql_dg");
          let dat ={
              page: (page ? page : 0),
              limit: (limit ? limit : null)
          };
          Public_Object.search(dg, dat, {
              "api_url": window.Api.sql.search,
              "callback":function(d){
                      d.forEach(function(v,i){
                          v.create_date = UnixToDateTime(v.create_date);
                          v.run_time = v.run_time ? UnixToDateTime(v.run_time) : '';
                      });
                      return d;
              }
          }, Sql_Task_Object.list);
   },
   "row_dbclick":function(rowIndex, rowData){ Sql_Task_Object.change(); },
   "change": function(act){
      let node = $("#change_sql_task");
      let tab = $("#sql_tabs");
      let obj = this.field(['title', 'val', 'create_date', 'note']);
      let row = null;
      let opt = Apps.dialog_opt();
      opt.title = "新增任务";
      opt.buttons = [];
      $.each(obj, function(i,v){ v.val(''); });

      if(!act){
         //修改
         row = $("#sql_dg").datagrid("getSelected");
         if(!row) return;
         Object.keys(obj).forEach(function(k){ obj[k].val(row[k]); });

         obj.create_date.val(row.create_date);

         opt.title = "修改任务信息 ID: " + row.id;
         opt.buttons.push({text:"执行",iconCls :'icon-t-terminal',handler:function(){
                 Sql_Task_Object.be_run();
         }});
      }

      node.data("row",row);

      opt.buttons.push({text:"确认",iconCls :'icon-ok',handler:function(){
             let dats = {
                "title":obj.title.val(),
                "val":Sql_Task_Object.editor ? Sql_Task_Object.editor.getValue() : obj.val.val(),
                "note":obj.note.val()
             };
             let api_url = window.Api.sql.add;
             if(row){
                   dats.id = row.id;
                   api_url = window.Api.sql.update;
             }

             get_dats(api_url, dats, function(d,err){
                    if(err) { Public_Object.alert('请求出错!');return;}
                    if(!d.status) Public_Object.alert(d.msg);
                    Sql_Task_Object.list();
             });
   	      	node.dialog('close');
   	    }});
        opt.buttons.push({text:"取消",iconCls :'icon-cancel',handler:function(){ node.dialog('close'); }});

      Apps.Dialog_Show(node, opt, function(){
           if( 'history' != $("#sql_tabs").tabs("getSelected").attr("dom") ){ Sql_Task_Object.editor.setValue(obj.val.val()); }
      });
   },
   "tab_select": function(title){
           switch(title){
             case "任务详情":
                   let dom = $(this).find('textarea[name="val"]');
                   if(!Sql_Task_Object.editor){
                        Sql_Task_Object.editor = window.CodeMirror.fromTextArea(dom[0], {mode:'text/x-mysql',indentWithTabs:true,smartIndent:true,matchBrackets:true});
                        Sql_Task_Object.editor.setSize('auto', 'calc(100% - 120px)');
                   }
                   if( Sql_Task_Object.editor.getValue().length < 1 ){
                        Sql_Task_Object.editor.setValue(dom.val());
                   }
                   Sql_Task_Object.editor.refresh();
             break;
             case "执行记录":
                   Sql_Task_Object.history();
             break;
           }
   },
   "history": function(){
         let row = $("#change_sql_task").data("row");
          let tab = $('#sql_tabs').tabs('getSelected');
         let node = tab.find("> div:nth-child(2)");
         node.find("> li").remove();
         $("#sql_console").text('');
         if(!row){return;}

         if('history' === tab.attr("dom")){

               get_dats(window.Api.sql.history,{"task_id":row.id},function(d){
                     if(d.status){
                          d.data.forEach(function(v,i){
                                let li = $("<li></li>");
                                li.text(UnixToDateTime(v.create_date));
                                li.data("raw",v);
                                li.click(function(){
                                       $(this).parent().find("li").removeClass('sel');
                                       $(this).addClass('sel');
                                       let raw = $(this).data("raw");
                                       $("#sql_console").text(raw.result);
                                });
                                node.append(li);
                          });
                      } else { Public_Object.alert(d.msg); }
               });
         }
   },
   "del": function(){
      let row = $("#sql_dg").datagrid("getSelected");
      if(!row) return;
      Public_Object.confirm({content:'<p>您确定要删除 "'+row.id+'"</p>'}, function(){
            let ret = getByRsync(window.Api.sql.del,{"id":row.id});
            if(!ret.status) Public_Object.alert(ret.msg);
            Sql_Task_Object.list();
      });
   },
   "be_run":function(){
           let run = $("#run");
           run.find("> div:last-child").hide();
           run.find("> div:first-child").show();
           run.css("background-color","rgba(0,0,0,0.5)");

           let obj = Apps.field(run.find("> div:first-child > div.input_list"), ['project_id','milieu_id']);
           obj.milieu_id.find('option:not(:first-child)').remove();
           window.Apps.data.milieu.forEach(function(v,i){
                 let opt = $('<option value=""></option>');
                 opt.val(v.id);
                 opt.text(v.milieu_name);
                 obj.milieu_id.append(opt);
           });

           obj.project_id.find('option:not(:first-child)').remove();
           window.Apps.data.project.forEach(function(v,i){
                 let opt = $('<option value=""></option>');
                 opt.val(v.id);
                 opt.text(v.project_name);
                 obj.project_id.append(opt);
           });


           run.show();
   },
   "run": function(){
           let run = $("#run");
           let obj = Apps.field(run.find("> div:first-child > div.input_list"), ['project_id','milieu_id']);
           run.find("> div:first-child").hide();
           run.find("> div:last-child").show();
           run.css("background-color","rgba(200,200,200)");

           let row = $("#change_sql_task").data("row");
           if(!row){console.log("发生错误! 未找到记录信息!"); return;}

           window.Wsock.send($("#run_console"), "sql_task", {"id":row.id, "project_id":parseInt(obj.project_id.val()), "milieu_id":parseInt(obj.milieu_id.val())});
   }
}
